package com.myserver.core;

import com.myserver.log.LoggerFactory;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.logging.Logger;

public class Response {
    private static final String CRLF = "\r\n";
    private static final String SPACE = " ";
    private StringBuilder header;
    private StringBuilder content;
    private BufferedWriter bw;
    private int lenth;
    final Logger logger = LoggerFactory.getLogger();

    public Response(OutputStream os){
        this.header = new StringBuilder();
        this.content = new StringBuilder();
        this.bw = new BufferedWriter(new OutputStreamWriter(os));
        this.lenth = 0;
    }
    private void createHeader(int code){
        header.append("HTTP/1.1").append(SPACE).append(code).append(SPACE);
        switch (code){
            case 200: header.append("OK");
            case 404: header.append("Not Found");
        }
        header.append(CRLF);
        header.append("Date: ").append(new Date()).append(CRLF);
        header.append("Server: ").append("localhost:8888").append(CRLF);
        header.append("Content-Type: ").append("text/html;charset=utf-8").append(CRLF);
        header.append("Content-Length: ").append(lenth).append(CRLF);
        header.append(CRLF);
    }
    public Response println(String line){
        content.append(line);
        this.lenth += line.length();
        return this;
    }
    public void flush(int code){
        createHeader(code);
        try {
            bw.append(header);
            bw.append(content);
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
